package com.ruoyi.learn.java.collection;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        // 1. 按键的自然顺序排序（字符串会按字典序）
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("banana", 2);
        treeMap.put("apple", 1);
        treeMap.put("cherry", 3);

        // 迭代时会按键的自然顺序输出：apple -> banana -> cherry
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // 2. 自定义比较器（例如按字符串长度排序）
        TreeMap<String, Integer> customOrderMap = new TreeMap<>((s1, s2) -> {
            return Integer.compare(s1.length(), s2.length()); // 按长度升序
        });
        customOrderMap.put("pear", 4);    // 4个字符
        customOrderMap.put("fig", 5);     // 3个字符
        customOrderMap.put("watermelon", 6); // 10个字符
        // 迭代顺序：fig -> pear -> watermelon
        // 迭代时会按键的自然顺序输出：apple -> banana -> cherry
        for (Map.Entry<String, Integer> entry : customOrderMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
